{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = ''\n",
    "os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import json\n",
    "import tensorflow as tf\n",
    "import itertools\n",
    "import collections\n",
    "import re\n",
    "import random\n",
    "import sentencepiece as spm\n",
    "from tqdm import tqdm\n",
    "import xlnet_utils as squad_utils\n",
    "import xlnet"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from prepro_utils import preprocess_text, encode_ids\n",
    "\n",
    "sp_model = spm.SentencePieceProcessor()\n",
    "sp_model.Load('sp10m.cased.v9.model')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "\n",
    "with open('/home/husein/xlnet/xlnet-squad-test.pkl', 'rb') as fopen:\n",
    "    test_features, test_examples = pickle.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "max_seq_length = 512\n",
    "doc_stride = 128\n",
    "max_query_length = 64"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "epoch = 5\n",
    "batch_size = 6\n",
    "warmup_proportion = 0.1\n",
    "n_best_size = 20\n",
    "num_train_steps = int(len(test_features) / batch_size * epoch)\n",
    "num_warmup_steps = int(num_train_steps * warmup_proportion)\n",
    "learning_rate = 2e-5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/alxlnet/xlnet.py:70: The name tf.gfile.Open is deprecated. Please use tf.io.gfile.GFile instead.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "kwargs = dict(\n",
    "      is_training=False,\n",
    "      use_tpu=False,\n",
    "      use_bfloat16=False,\n",
    "      dropout=0.1,\n",
    "      dropatt=0.1,\n",
    "      init='normal',\n",
    "      init_range=0.1,\n",
    "      init_std=0.05,\n",
    "      clamp_len=-1)\n",
    "\n",
    "xlnet_parameters = xlnet.RunConfig(**kwargs)\n",
    "xlnet_config = xlnet.XLNetConfig(\n",
    "    json_path = 'alxlnet-base-2020-04-10/config.json'\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "training_parameters = dict(\n",
    "      decay_method = 'poly',\n",
    "      train_steps = num_train_steps,\n",
    "      learning_rate = learning_rate,\n",
    "      warmup_steps = num_warmup_steps,\n",
    "      min_lr_ratio = 0.0,\n",
    "      weight_decay = 0.00,\n",
    "      adam_epsilon = 1e-8,\n",
    "      num_core_per_host = 1,\n",
    "      lr_layer_decay_rate = 1,\n",
    "      use_tpu=False,\n",
    "      use_bfloat16=False,\n",
    "      dropout=0.0,\n",
    "      dropatt=0.0,\n",
    "      init='normal',\n",
    "      init_range=0.1,\n",
    "      init_std=0.05,\n",
    "      clip = 1.0,\n",
    "      clamp_len=-1,)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Parameter:\n",
    "    def __init__(self, decay_method, warmup_steps, weight_decay, adam_epsilon, \n",
    "                num_core_per_host, lr_layer_decay_rate, use_tpu, learning_rate, train_steps,\n",
    "                min_lr_ratio, clip, **kwargs):\n",
    "        self.decay_method = decay_method\n",
    "        self.warmup_steps = warmup_steps\n",
    "        self.weight_decay = weight_decay\n",
    "        self.adam_epsilon = adam_epsilon\n",
    "        self.num_core_per_host = num_core_per_host\n",
    "        self.lr_layer_decay_rate = lr_layer_decay_rate\n",
    "        self.use_tpu = use_tpu\n",
    "        self.learning_rate = learning_rate\n",
    "        self.train_steps = train_steps\n",
    "        self.min_lr_ratio = min_lr_ratio\n",
    "        self.clip = clip\n",
    "        \n",
    "training_parameters = Parameter(**training_parameters)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensorflow.contrib import layers as contrib_layers\n",
    "\n",
    "class Model:\n",
    "    def __init__(self, is_training = True):\n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.segment_ids = tf.placeholder(tf.int32, [None, None])\n",
    "        self.input_masks = tf.placeholder(tf.float32, [None, None])\n",
    "        self.p_mask = tf.placeholder(tf.float32, [None, None])\n",
    "        self.cls_index = tf.placeholder(tf.int32, [None])\n",
    "        \n",
    "        xlnet_model = xlnet.XLNetModel(\n",
    "            xlnet_config=xlnet_config,\n",
    "            run_config=xlnet_parameters,\n",
    "            input_ids=tf.transpose(self.X, [1, 0]),\n",
    "            seg_ids=tf.transpose(self.segment_ids, [1, 0]),\n",
    "            input_mask=tf.transpose(self.input_masks, [1, 0]))\n",
    "        \n",
    "        output = xlnet_model.get_sequence_output()\n",
    "        self.output = output\n",
    "        self.vectorize = tf.identity(tf.transpose(output, [1, 0, 2]), name = 'logits_vectorize')\n",
    "        self.model = xlnet_model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/alxlnet/xlnet.py:253: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/alxlnet/xlnet.py:253: The name tf.AUTO_REUSE is deprecated. Please use tf.compat.v1.AUTO_REUSE instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/alxlnet/custom_modeling.py:697: The name tf.logging.info is deprecated. Please use tf.compat.v1.logging.info instead.\n",
      "\n",
      "INFO:tensorflow:memory input None\n",
      "INFO:tensorflow:Use float type <dtype: 'float32'>\n",
      "WARNING:tensorflow:From /home/husein/alxlnet/custom_modeling.py:704: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/alxlnet/custom_modeling.py:809: dropout (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.dropout instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:271: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/alxlnet/custom_modeling.py:109: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n"
     ]
    }
   ],
   "source": [
    "is_training = False\n",
    "\n",
    "tf.reset_default_graph()\n",
    "model = Model(is_training = is_training)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "start_n_top = 5\n",
    "end_n_top = 5\n",
    "seq_len = tf.shape(model.X)[1]\n",
    "initializer = model.model.get_initializer()\n",
    "return_dict = {}\n",
    "p_mask = model.p_mask\n",
    "output = model.output\n",
    "cls_index = model.cls_index\n",
    "\n",
    "with tf.variable_scope('start_logits'):\n",
    "    start_logits = tf.layers.dense(\n",
    "        output, 1, kernel_initializer = initializer\n",
    "    )\n",
    "    start_logits = tf.transpose(tf.squeeze(start_logits, -1), [1, 0])\n",
    "    start_logits_masked = start_logits * (1 - p_mask) - 1e30 * p_mask\n",
    "    start_log_probs = tf.nn.log_softmax(start_logits_masked, -1)\n",
    "    \n",
    "with tf.variable_scope('end_logits'):\n",
    "    if is_training:\n",
    "        # during training, compute the end logits based on the\n",
    "        # ground truth of the start position\n",
    "\n",
    "        start_positions = tf.reshape(model.start_positions, [-1])\n",
    "        start_index = tf.one_hot(\n",
    "            start_positions, depth = seq_len, axis = -1, dtype = tf.float32\n",
    "        )\n",
    "        start_features = tf.einsum('lbh,bl->bh', output, start_index)\n",
    "        start_features = tf.tile(start_features[None], [seq_len, 1, 1])\n",
    "        end_logits = tf.layers.dense(\n",
    "            tf.concat([output, start_features], axis = -1),\n",
    "            xlnet_config.d_model,\n",
    "            kernel_initializer = initializer,\n",
    "            activation = tf.tanh,\n",
    "            name = 'dense_0',\n",
    "        )\n",
    "        end_logits = tf.contrib.layers.layer_norm(\n",
    "            end_logits, begin_norm_axis = -1\n",
    "        )\n",
    "\n",
    "        end_logits = tf.layers.dense(\n",
    "            end_logits,\n",
    "            1,\n",
    "            kernel_initializer = initializer,\n",
    "            name = 'dense_1',\n",
    "        )\n",
    "        end_logits = tf.transpose(tf.squeeze(end_logits, -1), [1, 0])\n",
    "        end_logits_masked = end_logits * (1 - p_mask) - 1e30 * p_mask\n",
    "        end_log_probs = tf.nn.log_softmax(end_logits_masked, -1)\n",
    "    else:\n",
    "        # during inference, compute the end logits based on beam search\n",
    "\n",
    "        start_top_log_probs, start_top_index = tf.nn.top_k(\n",
    "            start_log_probs, k = start_n_top\n",
    "        )\n",
    "        start_index = tf.one_hot(\n",
    "            start_top_index, depth = seq_len, axis = -1, dtype = tf.float32\n",
    "        )\n",
    "        start_features = tf.einsum('lbh,bkl->bkh', output, start_index)\n",
    "        end_input = tf.tile(\n",
    "            output[:, :, None], [1, 1, start_n_top, 1]\n",
    "        )\n",
    "        start_features = tf.tile(start_features[None], [seq_len, 1, 1, 1])\n",
    "        end_input = tf.concat([end_input, start_features], axis = -1)\n",
    "        end_logits = tf.layers.dense(\n",
    "            end_input,\n",
    "            xlnet_config.d_model,\n",
    "            kernel_initializer = initializer,\n",
    "            activation = tf.tanh,\n",
    "            name = 'dense_0',\n",
    "        )\n",
    "        end_logits = tf.contrib.layers.layer_norm(\n",
    "            end_logits, begin_norm_axis = -1\n",
    "        )\n",
    "        end_logits = tf.layers.dense(\n",
    "            end_logits,\n",
    "            1,\n",
    "            kernel_initializer = initializer,\n",
    "            name = 'dense_1',\n",
    "        )\n",
    "        end_logits = tf.reshape(\n",
    "            end_logits, [seq_len, -1, start_n_top]\n",
    "        )\n",
    "        end_logits = tf.transpose(end_logits, [1, 2, 0])\n",
    "        end_logits_masked = (\n",
    "            end_logits * (1 - p_mask[:, None]) - 1e30 * p_mask[:, None]\n",
    "        )\n",
    "        end_log_probs = tf.nn.log_softmax(end_logits_masked, -1)\n",
    "        end_top_log_probs, end_top_index = tf.nn.top_k(\n",
    "            end_log_probs, k = end_n_top\n",
    "        )\n",
    "        end_top_log_probs = tf.reshape(\n",
    "            end_top_log_probs, [-1, start_n_top * end_n_top]\n",
    "        )\n",
    "        end_top_index = tf.reshape(\n",
    "            end_top_index, [-1, start_n_top * end_n_top]\n",
    "        )\n",
    "\n",
    "if is_training:\n",
    "    return_dict['start_log_probs'] = start_log_probs\n",
    "    return_dict['end_log_probs'] = end_log_probs\n",
    "else:\n",
    "    return_dict['start_top_log_probs'] = start_top_log_probs\n",
    "    return_dict['start_top_index'] = start_top_index\n",
    "    return_dict['end_top_log_probs'] = end_top_log_probs\n",
    "    return_dict['end_top_index'] = end_top_index\n",
    "\n",
    "# an additional layer to predict answerability\n",
    "with tf.variable_scope('answer_class'):\n",
    "    # get the representation of CLS\n",
    "    cls_index = tf.one_hot(\n",
    "        cls_index, seq_len, axis = -1, dtype = tf.float32\n",
    "    )\n",
    "    cls_feature = tf.einsum('lbh,bl->bh', output, cls_index)\n",
    "\n",
    "    # get the representation of START\n",
    "    start_p = tf.nn.softmax(\n",
    "        start_logits_masked, axis = -1, name = 'softmax_start'\n",
    "    )\n",
    "    start_feature = tf.einsum('lbh,bl->bh', output, start_p)\n",
    "\n",
    "    # note(zhiliny): no dependency on end_feature so that we can obtain\n",
    "    # one single `cls_logits` for each sample\n",
    "    ans_feature = tf.concat([start_feature, cls_feature], -1)\n",
    "    ans_feature = tf.layers.dense(\n",
    "        ans_feature,\n",
    "        xlnet_config.d_model,\n",
    "        activation = tf.tanh,\n",
    "        kernel_initializer = initializer,\n",
    "        name = 'dense_0',\n",
    "    )\n",
    "    ans_feature = tf.layers.dropout(\n",
    "        ans_feature, 0.1, training = is_training\n",
    "    )\n",
    "    cls_logits = tf.layers.dense(\n",
    "        ans_feature,\n",
    "        1,\n",
    "        kernel_initializer = initializer,\n",
    "        name = 'dense_1',\n",
    "        use_bias = False,\n",
    "    )\n",
    "    cls_logits = tf.squeeze(cls_logits, -1)\n",
    "\n",
    "    return_dict['cls_logits'] = cls_logits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Restoring parameters from alxlnet-base-squad/model.ckpt\n"
     ]
    }
   ],
   "source": [
    "sess = tf.InteractiveSession()\n",
    "sess.run(tf.global_variables_initializer())\n",
    "saver = tf.train.Saver(var_list = tf.trainable_variables())\n",
    "saver.restore(sess, 'alxlnet-base-squad/model.ckpt')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "start_top_log_probs = tf.identity(start_top_log_probs, name = 'start_top_log_probs')\n",
    "start_top_index = tf.identity(start_top_index, name = 'start_top_index')\n",
    "end_top_log_probs = tf.identity(end_top_log_probs, name = 'end_top_log_probs')\n",
    "end_top_index = tf.identity(end_top_index, name = 'end_top_index')\n",
    "cls_logits = tf.identity(cls_logits, name = 'cls_logits')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "i = 0\n",
    "batch_size = 2\n",
    "batch = test_features[i: i + batch_size]\n",
    "batch_ids = [b.input_ids for b in batch]\n",
    "batch_masks = [b.input_mask for b in batch]\n",
    "batch_segment = [b.segment_ids for b in batch]\n",
    "batch_start = [b.start_position for b in batch]\n",
    "batch_end = [b.end_position for b in batch]\n",
    "is_impossible = [b.is_impossible for b in batch]\n",
    "p_mask = [b.p_mask for b in batch]\n",
    "cls_index = [b.cls_index for b in batch]\n",
    "o = sess.run(\n",
    "    [start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits],\n",
    "    feed_dict = {\n",
    "        model.X: batch_ids,\n",
    "        model.segment_ids: batch_segment,\n",
    "        model.input_masks: batch_masks,\n",
    "        model.p_mask: p_mask,\n",
    "        model.cls_index: cls_index\n",
    "    },\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'output-alxlnet-base-squad/model.ckpt'"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "saver = tf.train.Saver(tf.trainable_variables())\n",
    "saver.save(sess, 'output-alxlnet-base-squad/model.ckpt')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Placeholder',\n",
       " 'Placeholder_1',\n",
       " 'Placeholder_2',\n",
       " 'Placeholder_3',\n",
       " 'Placeholder_4',\n",
       " 'model/transformer/r_w_bias',\n",
       " 'model/transformer/r_r_bias',\n",
       " 'model/transformer/word_embedding/lookup_table',\n",
       " 'model/transformer/word_embedding/lookup_table_2',\n",
       " 'model/transformer/r_s_bias',\n",
       " 'model/transformer/seg_embed',\n",
       " 'model/transformer/layer_shared/rel_attn/q/kernel',\n",
       " 'model/transformer/layer_shared/rel_attn/k/kernel',\n",
       " 'model/transformer/layer_shared/rel_attn/v/kernel',\n",
       " 'model/transformer/layer_shared/rel_attn/r/kernel',\n",
       " 'model/transformer/layer_shared/rel_attn/o/kernel',\n",
       " 'model/transformer/layer_shared/rel_attn/LayerNorm/gamma',\n",
       " 'model/transformer/layer_shared/ff/layer_1/kernel',\n",
       " 'model/transformer/layer_shared/ff/layer_1/bias',\n",
       " 'model/transformer/layer_shared/ff/layer_2/kernel',\n",
       " 'model/transformer/layer_shared/ff/layer_2/bias',\n",
       " 'model/transformer/layer_shared/ff/LayerNorm/gamma',\n",
       " 'logits_vectorize',\n",
       " 'start_logits/dense/kernel/Initializer/random_normal/shape',\n",
       " 'start_logits/dense/kernel/Initializer/random_normal/mean',\n",
       " 'start_logits/dense/kernel/Initializer/random_normal/stddev',\n",
       " 'start_logits/dense/kernel/Initializer/random_normal/RandomStandardNormal',\n",
       " 'start_logits/dense/kernel/Initializer/random_normal/mul',\n",
       " 'start_logits/dense/kernel/Initializer/random_normal',\n",
       " 'start_logits/dense/kernel',\n",
       " 'start_logits/dense/kernel/Assign',\n",
       " 'start_logits/dense/kernel/read',\n",
       " 'start_logits/dense/bias/Initializer/zeros',\n",
       " 'start_logits/dense/bias',\n",
       " 'start_logits/dense/bias/Assign',\n",
       " 'start_logits/dense/bias/read',\n",
       " 'start_logits/dense/Tensordot/axes',\n",
       " 'start_logits/dense/Tensordot/free',\n",
       " 'start_logits/dense/Tensordot/Shape',\n",
       " 'start_logits/dense/Tensordot/GatherV2/axis',\n",
       " 'start_logits/dense/Tensordot/GatherV2',\n",
       " 'start_logits/dense/Tensordot/GatherV2_1/axis',\n",
       " 'start_logits/dense/Tensordot/GatherV2_1',\n",
       " 'start_logits/dense/Tensordot/Const',\n",
       " 'start_logits/dense/Tensordot/Prod',\n",
       " 'start_logits/dense/Tensordot/Const_1',\n",
       " 'start_logits/dense/Tensordot/Prod_1',\n",
       " 'start_logits/dense/Tensordot/concat/axis',\n",
       " 'start_logits/dense/Tensordot/concat',\n",
       " 'start_logits/dense/Tensordot/stack',\n",
       " 'start_logits/dense/Tensordot/transpose',\n",
       " 'start_logits/dense/Tensordot/Reshape',\n",
       " 'start_logits/dense/Tensordot/transpose_1/perm',\n",
       " 'start_logits/dense/Tensordot/transpose_1',\n",
       " 'start_logits/dense/Tensordot/Reshape_1/shape',\n",
       " 'start_logits/dense/Tensordot/Reshape_1',\n",
       " 'start_logits/dense/Tensordot/MatMul',\n",
       " 'start_logits/dense/Tensordot/Const_2',\n",
       " 'start_logits/dense/Tensordot/concat_1/axis',\n",
       " 'start_logits/dense/Tensordot/concat_1',\n",
       " 'start_logits/dense/Tensordot',\n",
       " 'start_logits/dense/BiasAdd',\n",
       " 'start_logits/Squeeze',\n",
       " 'start_logits/transpose/perm',\n",
       " 'start_logits/transpose',\n",
       " 'start_logits/sub/x',\n",
       " 'start_logits/sub',\n",
       " 'start_logits/mul',\n",
       " 'start_logits/mul_1/x',\n",
       " 'start_logits/mul_1',\n",
       " 'start_logits/sub_1',\n",
       " 'start_logits/LogSoftmax',\n",
       " 'end_logits/TopKV2/k',\n",
       " 'end_logits/TopKV2',\n",
       " 'end_logits/one_hot/on_value',\n",
       " 'end_logits/one_hot/off_value',\n",
       " 'end_logits/one_hot',\n",
       " 'end_logits/einsum/transpose/perm',\n",
       " 'end_logits/einsum/transpose',\n",
       " 'end_logits/einsum/transpose_1/perm',\n",
       " 'end_logits/einsum/transpose_1',\n",
       " 'end_logits/einsum/Shape',\n",
       " 'end_logits/einsum/strided_slice/stack',\n",
       " 'end_logits/einsum/strided_slice/stack_1',\n",
       " 'end_logits/einsum/strided_slice/stack_2',\n",
       " 'end_logits/einsum/strided_slice',\n",
       " 'end_logits/einsum/strided_slice_1/stack',\n",
       " 'end_logits/einsum/strided_slice_1/stack_1',\n",
       " 'end_logits/einsum/strided_slice_1/stack_2',\n",
       " 'end_logits/einsum/strided_slice_1',\n",
       " 'end_logits/einsum/mul/x',\n",
       " 'end_logits/einsum/mul',\n",
       " 'end_logits/einsum/Reshape/shape/1',\n",
       " 'end_logits/einsum/Reshape/shape',\n",
       " 'end_logits/einsum/Reshape',\n",
       " 'end_logits/einsum/Shape_1',\n",
       " 'end_logits/einsum/strided_slice_2/stack',\n",
       " 'end_logits/einsum/strided_slice_2/stack_1',\n",
       " 'end_logits/einsum/strided_slice_2/stack_2',\n",
       " 'end_logits/einsum/strided_slice_2',\n",
       " 'end_logits/einsum/strided_slice_3/stack',\n",
       " 'end_logits/einsum/strided_slice_3/stack_1',\n",
       " 'end_logits/einsum/strided_slice_3/stack_2',\n",
       " 'end_logits/einsum/strided_slice_3',\n",
       " 'end_logits/einsum/Reshape_1/shape/2',\n",
       " 'end_logits/einsum/Reshape_1/shape',\n",
       " 'end_logits/einsum/Reshape_1',\n",
       " 'end_logits/einsum/MatMul',\n",
       " 'end_logits/einsum/Reshape_2/shape/1',\n",
       " 'end_logits/einsum/Reshape_2/shape/2',\n",
       " 'end_logits/einsum/Reshape_2/shape',\n",
       " 'end_logits/einsum/Reshape_2',\n",
       " 'end_logits/einsum/transpose_2/perm',\n",
       " 'end_logits/einsum/transpose_2',\n",
       " 'end_logits/strided_slice/stack',\n",
       " 'end_logits/strided_slice/stack_1',\n",
       " 'end_logits/strided_slice/stack_2',\n",
       " 'end_logits/strided_slice',\n",
       " 'end_logits/Tile/multiples',\n",
       " 'end_logits/Tile',\n",
       " 'end_logits/strided_slice_1/stack',\n",
       " 'end_logits/strided_slice_1/stack_1',\n",
       " 'end_logits/strided_slice_1/stack_2',\n",
       " 'end_logits/strided_slice_1',\n",
       " 'end_logits/Tile_1/multiples/1',\n",
       " 'end_logits/Tile_1/multiples/2',\n",
       " 'end_logits/Tile_1/multiples/3',\n",
       " 'end_logits/Tile_1/multiples',\n",
       " 'end_logits/Tile_1',\n",
       " 'end_logits/concat/axis',\n",
       " 'end_logits/concat',\n",
       " 'end_logits/dense_0/kernel/Initializer/random_normal/shape',\n",
       " 'end_logits/dense_0/kernel/Initializer/random_normal/mean',\n",
       " 'end_logits/dense_0/kernel/Initializer/random_normal/stddev',\n",
       " 'end_logits/dense_0/kernel/Initializer/random_normal/RandomStandardNormal',\n",
       " 'end_logits/dense_0/kernel/Initializer/random_normal/mul',\n",
       " 'end_logits/dense_0/kernel/Initializer/random_normal',\n",
       " 'end_logits/dense_0/kernel',\n",
       " 'end_logits/dense_0/kernel/Assign',\n",
       " 'end_logits/dense_0/kernel/read',\n",
       " 'end_logits/dense_0/bias/Initializer/zeros',\n",
       " 'end_logits/dense_0/bias',\n",
       " 'end_logits/dense_0/bias/Assign',\n",
       " 'end_logits/dense_0/bias/read',\n",
       " 'end_logits/dense_0/Tensordot/axes',\n",
       " 'end_logits/dense_0/Tensordot/free',\n",
       " 'end_logits/dense_0/Tensordot/Shape',\n",
       " 'end_logits/dense_0/Tensordot/GatherV2/axis',\n",
       " 'end_logits/dense_0/Tensordot/GatherV2',\n",
       " 'end_logits/dense_0/Tensordot/GatherV2_1/axis',\n",
       " 'end_logits/dense_0/Tensordot/GatherV2_1',\n",
       " 'end_logits/dense_0/Tensordot/Const',\n",
       " 'end_logits/dense_0/Tensordot/Prod',\n",
       " 'end_logits/dense_0/Tensordot/Const_1',\n",
       " 'end_logits/dense_0/Tensordot/Prod_1',\n",
       " 'end_logits/dense_0/Tensordot/concat/axis',\n",
       " 'end_logits/dense_0/Tensordot/concat',\n",
       " 'end_logits/dense_0/Tensordot/stack',\n",
       " 'end_logits/dense_0/Tensordot/transpose',\n",
       " 'end_logits/dense_0/Tensordot/Reshape',\n",
       " 'end_logits/dense_0/Tensordot/transpose_1/perm',\n",
       " 'end_logits/dense_0/Tensordot/transpose_1',\n",
       " 'end_logits/dense_0/Tensordot/Reshape_1/shape',\n",
       " 'end_logits/dense_0/Tensordot/Reshape_1',\n",
       " 'end_logits/dense_0/Tensordot/MatMul',\n",
       " 'end_logits/dense_0/Tensordot/Const_2',\n",
       " 'end_logits/dense_0/Tensordot/concat_1/axis',\n",
       " 'end_logits/dense_0/Tensordot/concat_1',\n",
       " 'end_logits/dense_0/Tensordot',\n",
       " 'end_logits/dense_0/BiasAdd',\n",
       " 'end_logits/dense_0/Tanh',\n",
       " 'end_logits/LayerNorm/gamma/Initializer/ones',\n",
       " 'end_logits/LayerNorm/gamma',\n",
       " 'end_logits/LayerNorm/gamma/Assign',\n",
       " 'end_logits/LayerNorm/gamma/read',\n",
       " 'end_logits/LayerNorm/moments/mean/reduction_indices',\n",
       " 'end_logits/LayerNorm/moments/mean',\n",
       " 'end_logits/LayerNorm/moments/StopGradient',\n",
       " 'end_logits/LayerNorm/moments/SquaredDifference',\n",
       " 'end_logits/LayerNorm/moments/variance/reduction_indices',\n",
       " 'end_logits/LayerNorm/moments/variance',\n",
       " 'end_logits/LayerNorm/batchnorm/add/y',\n",
       " 'end_logits/LayerNorm/batchnorm/add',\n",
       " 'end_logits/LayerNorm/batchnorm/Rsqrt',\n",
       " 'end_logits/LayerNorm/batchnorm/mul',\n",
       " 'end_logits/LayerNorm/batchnorm/mul_1',\n",
       " 'end_logits/LayerNorm/batchnorm/mul_2',\n",
       " 'end_logits/LayerNorm/batchnorm/sub',\n",
       " 'end_logits/LayerNorm/batchnorm/add_1',\n",
       " 'end_logits/dense_1/kernel/Initializer/random_normal/shape',\n",
       " 'end_logits/dense_1/kernel/Initializer/random_normal/mean',\n",
       " 'end_logits/dense_1/kernel/Initializer/random_normal/stddev',\n",
       " 'end_logits/dense_1/kernel/Initializer/random_normal/RandomStandardNormal',\n",
       " 'end_logits/dense_1/kernel/Initializer/random_normal/mul',\n",
       " 'end_logits/dense_1/kernel/Initializer/random_normal',\n",
       " 'end_logits/dense_1/kernel',\n",
       " 'end_logits/dense_1/kernel/Assign',\n",
       " 'end_logits/dense_1/kernel/read',\n",
       " 'end_logits/dense_1/bias/Initializer/zeros',\n",
       " 'end_logits/dense_1/bias',\n",
       " 'end_logits/dense_1/bias/Assign',\n",
       " 'end_logits/dense_1/bias/read',\n",
       " 'end_logits/dense_1/Tensordot/axes',\n",
       " 'end_logits/dense_1/Tensordot/free',\n",
       " 'end_logits/dense_1/Tensordot/Shape',\n",
       " 'end_logits/dense_1/Tensordot/GatherV2/axis',\n",
       " 'end_logits/dense_1/Tensordot/GatherV2',\n",
       " 'end_logits/dense_1/Tensordot/GatherV2_1/axis',\n",
       " 'end_logits/dense_1/Tensordot/GatherV2_1',\n",
       " 'end_logits/dense_1/Tensordot/Const',\n",
       " 'end_logits/dense_1/Tensordot/Prod',\n",
       " 'end_logits/dense_1/Tensordot/Const_1',\n",
       " 'end_logits/dense_1/Tensordot/Prod_1',\n",
       " 'end_logits/dense_1/Tensordot/concat/axis',\n",
       " 'end_logits/dense_1/Tensordot/concat',\n",
       " 'end_logits/dense_1/Tensordot/stack',\n",
       " 'end_logits/dense_1/Tensordot/transpose',\n",
       " 'end_logits/dense_1/Tensordot/Reshape',\n",
       " 'end_logits/dense_1/Tensordot/transpose_1/perm',\n",
       " 'end_logits/dense_1/Tensordot/transpose_1',\n",
       " 'end_logits/dense_1/Tensordot/Reshape_1/shape',\n",
       " 'end_logits/dense_1/Tensordot/Reshape_1',\n",
       " 'end_logits/dense_1/Tensordot/MatMul',\n",
       " 'end_logits/dense_1/Tensordot/Const_2',\n",
       " 'end_logits/dense_1/Tensordot/concat_1/axis',\n",
       " 'end_logits/dense_1/Tensordot/concat_1',\n",
       " 'end_logits/dense_1/Tensordot',\n",
       " 'end_logits/dense_1/BiasAdd',\n",
       " 'end_logits/Reshape/shape/1',\n",
       " 'end_logits/Reshape/shape/2',\n",
       " 'end_logits/Reshape/shape',\n",
       " 'end_logits/Reshape',\n",
       " 'end_logits/transpose/perm',\n",
       " 'end_logits/transpose',\n",
       " 'end_logits/strided_slice_2/stack',\n",
       " 'end_logits/strided_slice_2/stack_1',\n",
       " 'end_logits/strided_slice_2/stack_2',\n",
       " 'end_logits/strided_slice_2',\n",
       " 'end_logits/sub/x',\n",
       " 'end_logits/sub',\n",
       " 'end_logits/mul',\n",
       " 'end_logits/strided_slice_3/stack',\n",
       " 'end_logits/strided_slice_3/stack_1',\n",
       " 'end_logits/strided_slice_3/stack_2',\n",
       " 'end_logits/strided_slice_3',\n",
       " 'end_logits/mul_1/x',\n",
       " 'end_logits/mul_1',\n",
       " 'end_logits/sub_1',\n",
       " 'end_logits/LogSoftmax',\n",
       " 'end_logits/TopKV2_1/k',\n",
       " 'end_logits/TopKV2_1',\n",
       " 'end_logits/Reshape_1/shape',\n",
       " 'end_logits/Reshape_1',\n",
       " 'end_logits/Reshape_2/shape',\n",
       " 'end_logits/Reshape_2',\n",
       " 'answer_class/dense_0/kernel',\n",
       " 'answer_class/dense_0/bias',\n",
       " 'answer_class/dense_1/kernel',\n",
       " 'start_top_log_probs',\n",
       " 'start_top_index',\n",
       " 'end_top_log_probs',\n",
       " 'end_top_index',\n",
       " 'cls_logits']"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "strings = ','.join(\n",
    "    [\n",
    "        n.name\n",
    "        for n in tf.get_default_graph().as_graph_def().node\n",
    "        if ('Variable' in n.op\n",
    "        or 'Placeholder' in n.name\n",
    "        or 'logits' in n.name\n",
    "        or 'start_' in n.name\n",
    "        or 'end_' in n.name)\n",
    "        and 'adam' not in n.name\n",
    "        and 'beta' not in n.name\n",
    "        and 'global_step' not in n.name\n",
    "    ]\n",
    ")\n",
    "strings.split(',')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [],
   "source": [
    "def freeze_graph(model_dir, output_node_names):\n",
    "\n",
    "    if not tf.gfile.Exists(model_dir):\n",
    "        raise AssertionError(\n",
    "            \"Export directory doesn't exists. Please specify an export \"\n",
    "            'directory: %s' % model_dir\n",
    "        )\n",
    "\n",
    "    checkpoint = tf.train.get_checkpoint_state(model_dir)\n",
    "    input_checkpoint = checkpoint.model_checkpoint_path\n",
    "\n",
    "    absolute_model_dir = '/'.join(input_checkpoint.split('/')[:-1])\n",
    "    output_graph = absolute_model_dir + '/frozen_model.pb'\n",
    "    clear_devices = True\n",
    "    with tf.Session(graph = tf.Graph()) as sess:\n",
    "        saver = tf.train.import_meta_graph(\n",
    "            input_checkpoint + '.meta', clear_devices = clear_devices\n",
    "        )\n",
    "        saver.restore(sess, input_checkpoint)\n",
    "        output_graph_def = tf.graph_util.convert_variables_to_constants(\n",
    "            sess,\n",
    "            tf.get_default_graph().as_graph_def(),\n",
    "            output_node_names.split(','),\n",
    "        )\n",
    "        with tf.gfile.GFile(output_graph, 'wb') as f:\n",
    "            f.write(output_graph_def.SerializeToString())\n",
    "        print('%d ops in the final graph.' % len(output_graph_def.node))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Restoring parameters from output-alxlnet-base-squad/model.ckpt\n",
      "WARNING:tensorflow:From <ipython-input-20-9a7215a4e58a>:23: convert_variables_to_constants (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.compat.v1.graph_util.convert_variables_to_constants`\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/framework/graph_util_impl.py:277: extract_sub_graph (from tensorflow.python.framework.graph_util_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.compat.v1.graph_util.extract_sub_graph`\n",
      "INFO:tensorflow:Froze 30 variables.\n",
      "INFO:tensorflow:Converted 30 variables to const ops.\n",
      "6909 ops in the final graph.\n"
     ]
    }
   ],
   "source": [
    "freeze_graph('output-alxlnet-base-squad', strings)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "def load_graph(frozen_graph_filename):\n",
    "    with tf.gfile.GFile(frozen_graph_filename, 'rb') as f:\n",
    "        graph_def = tf.GraphDef()\n",
    "        graph_def.ParseFromString(f.read())\n",
    "        \n",
    "    for node in graph_def.node:\n",
    "        if node.op == 'RefSwitch':\n",
    "            node.op = 'Switch'\n",
    "            for index in xrange(len(node.input)):\n",
    "                if 'moving_' in node.input[index]:\n",
    "                    node.input[index] = node.input[index] + '/read'\n",
    "        elif node.op == 'AssignSub':\n",
    "            node.op = 'Sub'\n",
    "            if 'use_locking' in node.attr:\n",
    "                del node.attr['use_locking']\n",
    "        elif node.op == 'AssignAdd':\n",
    "            node.op = 'Add'\n",
    "            if 'use_locking' in node.attr:\n",
    "                del node.attr['use_locking']\n",
    "        elif node.op == 'Assign':\n",
    "            node.op = 'Identity'\n",
    "            if 'use_locking' in node.attr:\n",
    "                del node.attr['use_locking']\n",
    "            if 'validate_shape' in node.attr:\n",
    "                del node.attr['validate_shape']\n",
    "            if len(node.input) == 2:\n",
    "                node.input[0] = node.input[1]\n",
    "                del node.input[1]\n",
    "                \n",
    "    with tf.Graph().as_default() as graph:\n",
    "        tf.import_graph_def(graph_def)\n",
    "    return graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = load_graph('output-alxlnet-base-squad/frozen_model.pb')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "transforms = ['add_default_attributes',\n",
    "             'remove_nodes(op=Identity, op=CheckNumerics, op=Dropout)',\n",
    "             'fold_batch_norms',\n",
    "             'fold_old_batch_norms',\n",
    "             'quantize_weights(fallback_min=-10, fallback_max=10)',\n",
    "             'strip_unused_nodes',\n",
    "             'sort_by_execution_order']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensorflow.tools.graph_transforms import TransformGraph\n",
    "tf.set_random_seed(0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-27-998bb9729eac>:4: FastGFile.__init__ (from tensorflow.python.platform.gfile) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.gfile.GFile.\n"
     ]
    }
   ],
   "source": [
    "pb = 'output-alxlnet-base-squad/frozen_model.pb'\n",
    "\n",
    "input_graph_def = tf.GraphDef()\n",
    "with tf.gfile.FastGFile(pb, 'rb') as f:\n",
    "    input_graph_def.ParseFromString(f.read())\n",
    "    \n",
    "inputs = ['Placeholder', 'Placeholder_1', 'Placeholder_2', 'Placeholder_3', 'Placeholder_4']\n",
    "outputs = ['start_top_log_probs',\n",
    " 'start_top_index',\n",
    " 'end_top_log_probs',\n",
    " 'end_top_index',\n",
    " 'cls_logits',\n",
    " 'logits_vectorize']\n",
    "\n",
    "transformed_graph_def = TransformGraph(input_graph_def, \n",
    "                                           inputs,\n",
    "                                           outputs, transforms)\n",
    "\n",
    "with tf.gfile.GFile(f'{pb}.quantized', 'wb') as f:\n",
    "    f.write(transformed_graph_def.SerializeToString())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "g = load_graph('output-alxlnet-base-squad/frozen_model.pb.quantized')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_nodes = {i: g.get_tensor_by_name(f'import/{i}:0') for i in inputs}\n",
    "output_nodes = {i: g.get_tensor_by_name(f'import/{i}:0') for i in outputs}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/client/session.py:1750: UserWarning: An interactive session is already active. This can cause out-of-memory errors in some cases. You must explicitly call `InteractiveSession.close()` to release resources held by the other session(s).\n",
      "  warnings.warn('An interactive session is already active. This can '\n"
     ]
    }
   ],
   "source": [
    "test_sess = tf.InteractiveSession(graph = g)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [],
   "source": [
    "b = [batch_ids, batch_segment, batch_masks, p_mask, cls_index]\n",
    "b = {input_nodes[i]: b[no] for no, i in enumerate(inputs)}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [],
   "source": [
    "o = test_sess.run(\n",
    "    output_nodes, feed_dict = b,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'start_top_log_probs': array([[-0.01017361, -5.3508844 , -6.230524  , -7.0358524 , -7.1334867 ],\n",
       "        [-0.12347065, -2.545479  , -4.830178  , -5.2084336 , -5.41917   ]],\n",
       "       dtype=float32), 'start_top_index': array([[ 47, 190,  45,  46,  44],\n",
       "        [ 29,  28, 191,  24,  26]], dtype=int32), 'end_top_log_probs': array([[-1.0673070e-03, -6.8515882e+00, -1.2371474e+01, -1.3416997e+01,\n",
       "         -1.4230107e+01, -5.7099620e-05, -1.0555126e+01, -1.2802329e+01,\n",
       "         -1.2937642e+01, -1.3404304e+01, -4.9938989e-01, -1.3587554e+00,\n",
       "         -2.5299537e+00, -3.4406898e+00, -4.0150442e+00, -1.4348902e-01,\n",
       "         -2.6492026e+00, -2.8838952e+00, -5.4946475e+00, -7.2217665e+00,\n",
       "         -9.6618307e-01, -1.1195062e+00, -1.6656684e+00, -2.9643059e+00,\n",
       "         -3.5911660e+00],\n",
       "        [-1.7521942e-02, -4.3683023e+00, -5.9846005e+00, -6.4855165e+00,\n",
       "         -8.3603144e+00, -4.2344693e-02, -4.3113942e+00, -4.5560584e+00,\n",
       "         -4.6392651e+00, -6.5254221e+00, -2.0668755e-04, -1.0992020e+01,\n",
       "         -1.1302846e+01, -1.1685103e+01, -1.1686329e+01, -1.0686939e+00,\n",
       "         -1.2611568e+00, -2.4695027e+00, -2.6122954e+00, -3.1808593e+00,\n",
       "         -7.3619896e-01, -1.5142035e+00, -2.7094584e+00, -3.6378636e+00,\n",
       "         -3.6649237e+00]], dtype=float32), 'end_top_index': array([[ 47,  48,  49,  50,  46, 190,  47,  48,  50,  53,  47,  46,  48,\n",
       "          45,  42,  47,  46,  48,  45,  42,  48,  47,  46,  42,  45],\n",
       "        [ 36,  32,  33,  37,  34,  36,  32,  37,  33,  29, 191,  21,  50,\n",
       "          36, 168,  36,  37,  39,  42,  47,  36,  37,  39,  42,  28]],\n",
       "       dtype=int32), 'cls_logits': array([-4.5873976, -4.668168 ], dtype=float32), 'logits_vectorize': array([[[-0.94444275, -1.2613908 ,  0.12284657, ..., -2.7804942 ,\n",
       "          -0.5540787 , -0.6022805 ],\n",
       "         [-1.3667543 ,  0.40435368, -0.34586942, ..., -2.2287035 ,\n",
       "          -1.1160947 , -0.7859663 ],\n",
       "         [-1.4041777 ,  1.4120848 , -0.7227597 , ..., -2.604145  ,\n",
       "           0.50475824,  0.08274911],\n",
       "         ...,\n",
       "         [-1.3578826 ,  0.68827605, -0.53505075, ..., -1.7255512 ,\n",
       "          -0.07783309,  0.5256266 ],\n",
       "         [-1.2465287 ,  0.722971  , -0.59337336, ..., -1.6875141 ,\n",
       "          -0.17212898,  0.6117162 ],\n",
       "         [-1.2339908 ,  0.7550968 , -0.5528449 , ..., -1.7461457 ,\n",
       "          -0.34921303,  0.6028584 ]],\n",
       " \n",
       "        [[-0.9457817 , -1.9634529 ,  0.00904389, ..., -1.7923499 ,\n",
       "          -0.4057198 , -0.23756696],\n",
       "         [-1.6259248 , -0.4892962 ,  0.6093696 , ..., -2.3416724 ,\n",
       "          -1.0541323 , -0.4906643 ],\n",
       "         [-1.6250538 ,  1.5278697 , -0.6941852 , ..., -2.6264231 ,\n",
       "          -0.16848056, -0.6517208 ],\n",
       "         ...,\n",
       "         [-1.5976688 ,  0.5064354 , -0.27355823, ..., -1.4438447 ,\n",
       "           0.14123085,  0.33396456],\n",
       "         [-1.5468978 ,  0.4436091 , -0.3208281 , ..., -1.3580312 ,\n",
       "           0.19130616,  0.5275669 ],\n",
       "         [-1.5788547 ,  0.37651774, -0.38421923, ..., -1.3529634 ,\n",
       "           0.1863327 ,  0.55256706]]], dtype=float32)}"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "o"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
